<script setup>
import {
  Back, Location, CreditCard, Plus
} from '@element-plus/icons-vue'
import VueQrcode from '@chenfengyuan/vue-qrcode';
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router';
import { productGetDetailServcie } from '@/api/product';
import { useRoute } from 'vue-router';
import { cartPostItemService } from '@/api/cart';
import { ElMessage } from 'element-plus';
import { orderGetIsPaidService, orderPostService } from '@/api/order';
import { addressGetDefaultService } from '@/api/address';

const router = useRouter();
const route = useRoute();

// 控制对话框显示
const showPurchaseDialog = ref(false);
const showAddressDialog = ref(false);
const showPayQrcodeDialog = ref(false);
const qrcodeUrl = ref('');

// 用户当前选中的收货地址
const userAddress = ref({});
const getUserAddress = async () => {
  userAddress.value = (await addressGetDefaultService()).data.data;
}
getUserAddress();

const onSelectAddress = (selecteAddress) => {
  userAddress.value = selecteAddress;
}

// 选中的支付方式
const selectedPayment = ref('alipay');

onMounted(() => {
  document.documentElement.classList.remove('dark');
})
onUnmounted(() => {
  document.documentElement.classList.add('dark');
  if (getOrderStatusTimer) {
    clearInterval(getOrderStatusTimer);
  }
})

/* 接收传参 */
const productId = route.query.id;

// 获取商品详细数据
const skuList = ref([]);
const specKeyValueListMap = reactive(new Map());
const getProductDetail = async () => {
  const res = await productGetDetailServcie(productId);
  productDetail.value = res.data.data;
  const { skus } = productDetail.value;
  skuList.value = skus;

  if (skuList.value) {
    for (const sku of skuList.value) {
      for (const spec of sku['specs']) {
          if (!specKeyValueListMap.has(spec.key)) {
            specKeyValueListMap.set(spec.key, new Set());
          }
          specKeyValueListMap.get(spec.key).add(spec.value);
      }
    }
    // 为每个 key 创建 "已选中的 value" 映射
    for (const specKey of specKeyValueListMap.keys()) {
      specKeySeletedValue[specKey] = '';
    }
  }
}
getProductDetail();


// 商品数据
const productDetail = ref({
  product_id: 0,
  title: '商品标题',
  description: '商品描述',
  price: 0,
  stock: 0,
  carousels: [
  ],
  skus: [
    { 
      sku_id: 0, 
      spec: [],
      price: 0,
      stock: 0,
    },
  ],
})

// 当前每个规格对应的规格值
const specKeySeletedValue = reactive({});
// 购买数量
const quantity = ref(1)

// 当前选中的 SKU
const selectedSku = computed(() => {
  if (!skuList.value) {
    return null;
  }
  for (const sku of skuList.value) {
    let isMatch = true;
    for (const spec of sku['specs']) {
      if (specKeySeletedValue[spec.key] != spec.value) {
        isMatch = false;
        break;
      }
    }
    if (isMatch) {
      return sku;
    }
  }
  return null;
})

/* 加入购物车 */
const addToCart = async () => {
  if (!selectedSku.value) {
    ElMessage.warning('请选择商品规格');
    return;
  }
  
  const selectedSkuObj = {}
  for (const spec of selectedSku.value.specs) {
    selectedSkuObj[spec['key']] = spec['value'];
  }
  const selectedSkuJson = JSON.stringify(selectedSkuObj);
  
  await cartPostItemService(productId, selectedSku.value.skuId,
    quantity.value, selectedSku.value.price, selectedSkuJson);
  
  ElMessage.success('已加入购物车');
}

// 立即购买
const buyNow = () => {
  if (!selectedSku.value) {
    ElMessage.warning('请选择商品规格');
    return;
  }
  
  if (selectedSku.value.stock <= 0) {
    ElMessage.warning('该规格商品已售罄');
    return;
  }
  
  showPurchaseDialog.value = true;
}

// 提交订单
let getOrderStatusTimer = null;
const orderForm = {
  productId: -1,
  skuId: -1,
  sku: '',
  deliveryAddress: '',
  quantity: -1
};
watch(showPayQrcodeDialog, (newValue) => {
  if (!newValue && getOrderStatusTimer) {
    clearInterval(getOrderStatusTimer)
    getOrderStatusTimer = null;
  }
})
const submitOrder = async () => {
  orderForm.productId = productId;
  orderForm.skuId = selectedSku.value.skuId;
  orderForm.quantity = quantity.value;
  const skuObj = {};
  for (const spec of selectedSku.value.specs) {
    skuObj[spec.key] = spec.value;
  }
  orderForm.sku = JSON.stringify(skuObj);
  const deliveryAddressObj = {};
  deliveryAddressObj['province'] = userAddress.value.province;
  deliveryAddressObj['city'] = userAddress.value.city;
  deliveryAddressObj['district'] = userAddress.value.district;
  deliveryAddressObj['detailAddress'] = userAddress.value.detailAddress;
  orderForm.deliveryAddress = JSON.stringify(deliveryAddressObj);
  const res = await orderPostService(orderForm);
  const { orderId, payUrl } = res.data.data;

  showAddressDialog.value = false;
  showPurchaseDialog.value = false;
  qrcodeUrl.value = payUrl;
  showPayQrcodeDialog.value = true;

  getOrderStatusTimer = setInterval(async () => {
   const res = await orderGetIsPaidService(orderId);
   if (res.data.data) {
    showPayQrcodeDialog.value = false;
    ElMessage.success('支付成功！');
   }
  }, 2000);
}
</script>

<template>
  <el-header class="app-header">
    <el-icon @click="router.back()"><Back /></el-icon>
    <div class="header-title">商品详情</div>
    <div class="header-action"></div>
  </el-header>
  
  <div class="product-detail-container">
    <!-- 商品主图/视频区 -->
    <el-row :gutter="30">
      <el-col :sm="24" :md="12">
        <div class="media-section">
          <el-carousel indicator-position="outside" height="500px">
            <el-carousel-item v-for="(url, index) in productDetail.carousels" :key="index">
              <img :src="url" class="media-content" />
            </el-carousel-item>
          </el-carousel>
        </div>
      </el-col>

      <!-- 商品信息区 -->
      <el-col :sm="24" :md="12">
        <div class="info-section">
          <div class="product-header">
            <el-tag type="danger" size="large" effect="dark" v-if="productDetail.is_hot">热销</el-tag>
            <h1 class="product-title">{{ productDetail.title }}</h1>
          </div>
          
          <div class="meta-info">
            <span>销量 {{ productDetail.sales || 0 }}</span>
            <el-divider direction="vertical" />
            <span>库存 {{ productDetail.stock || 0 }}</span>
          </div>

          <el-divider />

          <div class="price-section">
            <span class="price">
              ¥<strong>{{ selectedSku ? selectedSku.price : 0 }}</strong>
            </span>
            <span class="original-price" v-if="selectedSku && selectedSku.original_price">
              ¥{{ selectedSku.original_price }}
            </span>
          </div>

          <!-- 规格选择 -->
          <div class="sku-section" v-for="specKey in specKeyValueListMap.keys()" :key="specKey">
            <h3>{{ specKey }}</h3>
            <el-radio-group 
              v-model="specKeySeletedValue[specKey]"
              class="spec-group"
            >
              <el-radio-button 
                v-for="specValue in specKeyValueListMap.get(specKey)" 
                :label="specValue"
                :key="specValue"
              >
                <div class="sku-item">
                  {{ specValue }}
                </div>
              </el-radio-button>
            </el-radio-group>
          </div>

          <!-- 数量选择 -->
          <div class="quantity-section">
            <h3>数量</h3>
            <el-input-number 
              v-model="quantity" 
              :min="1" 
              :max="selectedSku ? selectedSku.stock : 10" 
              size="large"
              controls-position="right"
            />
            <div class="stock-hint" v-if="selectedSku">
              <span v-if="selectedSku.stock > 100">库存充足</span>
              <span v-else-if="selectedSku.stock > 0">仅剩 {{ selectedSku.stock }} 件</span>
              <span v-else class="out-of-stock">已售罄</span>
            </div>
          </div>

          <!-- 操作区 -->
          <div class="action-section">
            <el-button 
              type="danger" 
              size="large"
              class="action-btn"
              :disabled="!selectedSku || selectedSku.stock <= 0 || quantity <= 0"
              @click="addToCart"
            >
              <el-icon><ShoppingCart /></el-icon>
              加入购物车
            </el-button>
            <el-button 
              type="warning" 
              size="large"
              class="action-btn buy-btn"
              :disabled="!selectedSku || selectedSku.stock <= 0 || quantity <= 0"
              @click="buyNow"
            >
              立即购买
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 商品描述 -->
    <div class="description-section">
      <el-tabs type="border-card" class="detail-tabs">
        <el-tab-pane label="商品详情">
          <div v-html="productDetail.description" class="product-description"></div>
        </el-tab-pane>
        <el-tab-pane label="用户评价">
          <div class="review-placeholder">
            <el-image src="https://img.alicdn.com/imgextra/i3/O1CN01P4qA7p1H6VW1dCxXp_!!6000000000706-2-tps-600-300.png" />
            <p>暂无评价内容</p>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 购买对话框 -->
    <el-dialog 
      v-model="showPurchaseDialog" 
      title="确认订单" 
      width="50%"
      class="purchase-dialog"
    >
      <div class="order-summary">
        <div class="product-info">
          <el-image :src="productDetail.carousels[0]" class="product-thumb" />
          <div class="product-detail">
            <h4>{{ productDetail.title }}</h4>
            <p class="spec" v-if="selectedSku">
              {{ selectedSku.specs.map(s => s.value).join(' ') }}
            </p>
            <div class="price">¥{{ selectedSku ? selectedSku.price : 0 }} x {{ quantity }}</div>
          </div>
        </div>
        <div class="total-price">
          小计: <span class="amount">¥{{ selectedSku ? (selectedSku.price * quantity).toFixed(2) : '0.00' }}</span>
        </div>
      </div>
      
      <el-divider />
      
      <!-- 收货地址 -->
      <div class="address-section">
        <h3>收货地址</h3>
        <div class="address-list">
          <el-card 
            v-if="userAddress"
            class="address-card"
            @click="showAddressDialog = true"
          >
            <div class="address-header">
              <span>{{ userAddress.receiverName }}</span>
              <span>{{ userAddress.receiverPhone }}</span>
            </div>
            <div class="address-detail">
              {{ userAddress.province }} {{ userAddress.city }} {{ userAddress.district }} {{ userAddress.detailAddress }}
            </div>
          </el-card>
          <el-card v-else class="address-card" @click="showAddressDialog = true">
            点击添加地址
          </el-card>
        </div>
      </div>
      
      <el-divider />
      
      <!-- 支付方式 -->
      <div class="payment-section">
        <h3>支付方式</h3>
        <el-radio-group v-model="selectedPayment" class="payment-methods">
          <el-radio label="alipay">
            <el-icon>
              <svg t="1748952417349" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4367" width="200" height="200"><path d="M1024.0512 701.0304V196.864A196.9664 196.9664 0 0 0 827.136 0H196.864A196.9664 196.9664 0 0 0 0 196.864v630.272A196.9152 196.9152 0 0 0 196.864 1024h630.272a197.12 197.12 0 0 0 193.8432-162.0992c-52.224-22.6304-278.528-120.32-396.4416-176.64-89.7024 108.6976-183.7056 173.9264-325.3248 173.9264s-236.1856-87.2448-224.8192-194.048c7.4752-70.0416 55.552-184.576 264.2944-164.9664 110.08 10.3424 160.4096 30.8736 250.1632 60.5184 23.1936-42.5984 42.496-89.4464 57.1392-139.264H248.064v-39.424h196.9152V311.1424H204.8V267.776h240.128V165.632s2.1504-15.9744 19.8144-15.9744h98.4576V267.776h256v43.4176h-256V381.952h208.8448a805.9904 805.9904 0 0 1-84.8384 212.6848c60.672 22.016 336.7936 106.3936 336.7936 106.3936zM283.5456 791.6032c-149.6576 0-173.312-94.464-165.376-133.9392 7.8336-39.3216 51.2-90.624 134.4-90.624 95.5904 0 181.248 24.4736 284.0576 74.5472-72.192 94.0032-160.9216 150.016-253.0816 150.016z" fill="#009FE8" p-id="4368"></path></svg>
            </el-icon>
            <span>支付宝</span>
          </el-radio>
        </el-radio-group>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <div class="order-total">
            总计: <span class="total-amount">¥{{ selectedSku ? (selectedSku.price * quantity).toFixed(2) : '0.00' }}</span>
          </div>
          <el-button type="warning" size="large" @click="submitOrder">提交订单</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 地址管理对话框 -->
    <AddressDialog v-model="showAddressDialog" :canSelect="true" :onSelect="onSelectAddress"></AddressDialog>

    <el-dialog v-model="showPayQrcodeDialog">
      <div style="display: flex; align-items: center; justify-content: center;">
        <vue-qrcode :value="qrcodeUrl"></vue-qrcode>
      </div>
    </el-dialog>

  </div>
</template>

<style lang="scss" scoped>
.app-header {
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 60px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  background: white;
  z-index: 100;
  
  .el-icon {
    font-size: 22px;
    color: #666;
    cursor: pointer;
    margin-right: 10px;
  }
  
  .header-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
}

.product-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);

  .media-section {
    background: #f9f9f9;
    border-radius: 12px;
    overflow: hidden;
    
    .media-content {
      width: 100%;
      height: 500px;
      object-fit: contain;
      background: white;
    }
  }

  .info-section {
    padding: 0 20px;
    
    .product-header {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 15px;
      
      .el-tag {
        font-weight: bold;
        height: 28px;
        line-height: 28px;
      }
      
      .product-title {
        font-size: 24px;
        font-weight: 700;
        color: #333;
        line-height: 1.4;
        margin: 0;
      }
    }

    .meta-info {
      display: flex;
      align-items: center;
      gap: 12px;
      color: #666;
      font-size: 14px;
      margin-bottom: 15px;
    }

    .price-section {
      margin: 20px 0;
      display: flex;
      align-items: baseline;
      gap: 10px;
      
      .price {
        font-size: 28px;
        color: #ff5000;
        font-weight: bold;
        
        strong {
          font-size: 32px;
        }
      }
      
      .original-price {
        font-size: 16px;
        color: #999;
        text-decoration: line-through;
      }
    }

    .sku-section {
      margin: 25px 0;
      
      h3 {
        font-size: 16px;
        color: #666;
        margin-bottom: 12px;
      }
      
      .spec-group {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        
        :deep(.el-radio-button) {
          .el-radio-button__inner {
            border-radius: 4px;
            padding: 8px 15px;
            border: 1px solid #e5e5e5;
          }
          
          &.is-active {
            .el-radio-button__inner {
              background: #e9f5ff;
              border-color: #409eff;
              color: #409eff;
              box-shadow: none;
            }
          }
        }
      }
    }
    
    .quantity-section {
      display: flex;
      align-items: center;
      margin: 30px 0;
      
      h3 {
        font-size: 16px;
        color: #666;
        margin-right: 15px;
        width: 60px;
      }
      
      :deep(.el-input-number) {
        width: 140px;
        
        .el-input__inner {
          text-align: left;
        }
      }
      
      .stock-hint {
        margin-left: 15px;
        font-size: 14px;
        color: #666;
        
        .out-of-stock {
          color: #ff5000;
          font-weight: bold;
        }
      }
    }

    .action-section {
      margin-top: 30px;
      display: flex;
      gap: 15px;
      
      .action-btn {
        flex: 1;
        height: 48px;
        font-weight: bold;
        font-size: 16px;
        border-radius: 4px;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        
        &.buy-btn {
          background: linear-gradient(to right, #ff9000, #ff5000);
          border: none;
          color: white;
          
          &:hover {
            opacity: 0.9;
          }
        }
      }
    }
  }

  .description-section {
    margin-top: 50px;
    
    .detail-tabs {
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      :deep(.el-tabs__header) {
        background: #f5f7fa;
      }
      
      .product-description {
        padding: 20px;
      }
      
      .review-placeholder {
        text-align: center;
        padding: 40px 0;
        
        .el-image {
          width: 300px;
          opacity: 0.6;
        }
        
        p {
          color: #999;
          font-size: 16px;
        }
      }
    }
  }
  
  // 购买对话框样式
  .purchase-dialog {
    :deep(.el-dialog) {
      border-radius: 12px;
      overflow: hidden;
    }
    
    :deep(.el-dialog__header) {
      background: linear-gradient(to right, #ff9000, #ff5000);
      margin: 0;
      
      .el-dialog__title {
        color: white;
        font-weight: bold;
      }
      
      .el-dialog__headerbtn {
        color: white;
        
        &:hover {
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
    
    :deep(.el-dialog__body) {
      padding: 25px;
    }
    
    .order-summary {
      .product-info {
        display: flex;
        gap: 15px;
        
        .product-thumb {
          width: 80px;
          height: 80px;
          border-radius: 6px;
          border: 1px solid #eee;
          background: #f9f9f9;
        }
        
        .product-detail {
          flex: 1;
          
          h4 {
            margin: 0 0 8px;
            font-size: 16px;
            color: #333;
          }
          
          .spec {
            color: #666;
            font-size: 14px;
            margin: 0 0 8px;
          }
          
          .price {
            font-size: 16px;
            color: #ff5000;
            font-weight: bold;
          }
        }
      }
      
      .total-price {
        text-align: right;
        margin-top: 10px;
        font-size: 16px;
        
        .amount {
          font-size: 20px;
          color: #ff5000;
          font-weight: bold;
        }
      }
    }
    
    .address-section {
      h3 {
        font-size: 16px;
        color: #333;
        margin-bottom: 15px;
      }
      
      .address-list {
        display: flex;
        gap: 15px;
        overflow-x: auto;
        padding: 10px 0;
        
        .address-card {
          width: 280px;
          flex-shrink: 0;
          cursor: pointer;
          border-radius: 8px;
          transition: all 0.3s;
          border: 1px solid #e6e6e6;
          
          &.add-card {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: #409eff;
            background: #f5f9ff;
            
            .el-icon {
              margin-bottom: 10px;
            }
            
            p {
              margin: 0;
              font-size: 14px;
            }
          }
          
          .address-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 8px;
            
            .el-tag {
              margin-left: auto;
            }
          }
          
          .address-detail {
            color: #666;
            font-size: 14px;
            line-height: 1.4;
          }
        }
      }
    }
    
    .payment-section {
      h3 {
        font-size: 16px;
        color: #333;
        margin-bottom: 15px;
      }
      
      .payment-methods {
        display: flex;
        flex-direction: column;
        justify-content: center;
        gap: 15px;
        
        .el-radio {
          display: flex;
          align-items: center;
          padding: 12px 15px;
          border: 1px solid #e6e6e6;
          border-radius: 6px;
          transition: all 0.3s;
          margin: 0;
          :deep(.el-radio__label) {
            display: flex;
            align-items: center;
          }
          
          &.is-checked {
            border-color: #409eff;
            background: #f0f7ff;
          }
          
          .payment-icon {
            width: 30px;
            height: 30px;
          }
        }
      }
    }
    
    .dialog-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .order-total {
        font-size: 18px;
        
        .total-amount {
          font-size: 24px;
          color: #ff5000;
          font-weight: bold;
        }
      }
      
      .el-button {
        width: 180px;
        font-size: 16px;
        font-weight: bold;
        background: linear-gradient(to right, #ff9000, #ff5000);
        border: none;
        color: white;
        height: 48px;
        
        &:hover {
          opacity: 0.9;
        }
      }
    }
  }
}

// 响应式调整
@media (max-width: 992px) {
  .product-detail-container {
    padding: 10px;
    
    .info-section {
      padding: 0 10px;
    }
    
    .media-section .media-content {
      height: 300px;
    }
    
    .purchase-dialog {
      :deep(.el-dialog) {
        width: 90% !important;
      }
    }
    
    .action-section {
      .action-btn {
        font-size: 14px !important;
        padding: 0 10px;
      }
    }
  }
}

@media (max-width: 768px) {
  .info-section {
    margin-top: 20px;
  }
  
  .purchase-dialog {
    :deep(.el-dialog) {
      max-width: 100% !important;
      margin: 10px;
    }
  }
}
</style>